package com.yonyou.chuan.impl;

import cn.hutool.http.HttpUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.yonyou.chuan.constant.Constant;
import com.yonyou.chuan.log.LoggerUtil;
import com.yonyou.chuan.model.param.NxQxgParam;
import com.yonyou.chuan.model.param.YonBipParam;
import com.yonyou.chuan.model.subscribe.YonSubscribeContentDetail;
import com.yonyou.chuan.model.vo.YhtFlowVO;
import com.yonyou.chuan.service.MessageService;
import com.yonyou.chuan.service.YhtPubService;
import com.yonyou.chuan.util.QxgTokenUtil;
import nc.bs.dao.BaseDAO;
import nc.bs.framework.common.NCLocator;

import java.util.Base64;

public class MessageServiceImpl implements MessageService {
    private static BaseDAO basedao = null;

    public synchronized BaseDAO getBaseDao() {
        if (basedao == null) {
            basedao = new BaseDAO();
        }
        return basedao;
    }
    @Override
    public void sendTodoMessage(String content, NxQxgParam nxQxgParam, YonBipParam yonPublicParam) throws Exception {
        String ContentValue = JSONUtil.parseObj(content).getStr("value");
        YonSubscribeContentDetail detail = JSONUtil.toBean(ContentValue, YonSubscribeContentDetail.class);
        LoggerUtil.printLogger("【7小哥聚合平台系统待办推送】,跳转地址: {}",detail.getWebUrl());
        String businessKey = detail.getBusinessKey(); // businessKey sm_msg_approve.pk_detail = pub_workflownote.pk_checkflow
        YhtFlowVO flowVO = NCLocator.getInstance().lookup(YhtPubService.class).queryWorkFlow(businessKey);


        JSONObject json = new JSONObject();
        json.put("syscode", "泛微提供的系统编码");
        json.put("flowid", businessKey);
        json.put("requestname", flowVO.getSubject());
        json.put("nodename", "NC65");
        json.put("createdatetime", flowVO.getSendtime());
        json.put("workflowname", flowVO.getBillTypeName());

        json.put("creator", flowVO.getSubmiter().getUserMobile());
        json.put("receiver", flowVO.getRecipient().getUserMobile());

        json.put("receivedatetime", flowVO.getSendtime());
        json.put("isremark", "0".equals(flowVO.getFlowType()) ? "0" :"2" );
        json.put("viewtype", "0");
        json.put("receivets", String.valueOf(System.currentTimeMillis()));
        //uc审批 or portal
        json.put("pcurl", "");
        //移动审批
        String yhtpath = "https://c2.yonyoucloud.com/yonbip-ec-commonapprove/ucf-wh/mobileApprove/index.html#/detail?status=0&taskId="+businessKey;
        String yhttodo = Base64.getEncoder().encodeToString(yhtpath.getBytes());
        json.put("appurl", "/yhtlogin.jsp?target="+ yhttodo);
        LoggerUtil.printLogger("【待办推送】,单据类型:{},单据编号:{},提交人:{},审批人:{}",flowVO.getBillTypeName(),flowVO.getBillNo(),flowVO.getSubmiter().getUserName(),flowVO.getRecipient().getUserName());
        //TODO 发送请求
        LoggerUtil.printLogger("【待办推送】,请求地址: {}",nxQxgParam.getQxg_origin() + NxQxgParam.todoApi);
        LoggerUtil.printLogger("【待办推送】,请求报文: {}",json.toString());
        String accessToken = QxgTokenUtil.getToken(nxQxgParam.getQxg_origin() + NxQxgParam.tokenApi,nxQxgParam.getQxg_appKey(),nxQxgParam.getQxg_secret());
        String resp = HttpUtil.createPost(nxQxgParam.getQxg_origin() + NxQxgParam.todoApi).header("Content-Type", "application/json").header("Authorization", accessToken).body(json.toString()).execute().body();
        //TODO 打印响应结果
        LoggerUtil.printLogger("【待办推送】,响应报文: {}",resp);
        JSONObject todoResult = JSONUtil.parseObj(resp);
        if(Constant.FW_SUCCESS_CODE != todoResult.getStr("operResult")){
            throw new RuntimeException("【待办推送】,报错:"+todoResult.getStr("data"));
        }
    }

    @Override
    public void updateTodoMessage(String content, NxQxgParam nxQxgParam,YonBipParam yonPublicParam) throws Exception {
        String ContentValue = JSONUtil.parseObj(content).getStr("value");
        YonSubscribeContentDetail detail = JSONUtil.toBean(ContentValue, YonSubscribeContentDetail.class);
        LoggerUtil.printLogger("【7小哥聚合平台系统待办推送】,跳转地址: {}", detail.getWebUrl());
        String businessKey = detail.getBusinessKey(); // businessKey sm_msg_approve.pk_detail = pub_workflownote.pk_checkflow
        YhtFlowVO flowVO = NCLocator.getInstance().lookup(YhtPubService.class).queryWorkFlow(businessKey);


        JSONObject json = new JSONObject();
        json.put("syscode", "泛微提供的系统编码");
        json.put("flowid", businessKey);
        json.put("requestname", flowVO.getSubject());
        json.put("nodename", "NC65");
        json.put("createdatetime", flowVO.getSendtime());
        json.put("workflowname", flowVO.getBillTypeName());

        json.put("creator", flowVO.getSubmiter().getUserMobile());
        json.put("receiver", flowVO.getRecipient().getUserMobile());

        json.put("receivedatetime", flowVO.getSendtime());
        json.put("isremark", "0".equals(flowVO.getFlowType()) ? "0" : "2");
        json.put("viewtype", "0");
        json.put("receivets", String.valueOf(System.currentTimeMillis()));
        //uc审批 or portal
        json.put("pcurl", "");
        String yhtpath = "https://c2.yonyoucloud.com/yonbip-ec-commonapprove/ucf-wh/mobileApprove/index.html#/detail?status=1&taskId="+businessKey;
        String yhtdone = Base64.getEncoder().encodeToString(yhtpath.getBytes());
        json.put("appurl", "/yhtlogin.jsp?target="+ yhtdone);
        LoggerUtil.printLogger("【待办推送】,单据类型:{},单据编号:{},提交人:{},审批人:{}", flowVO.getBillTypeName(), flowVO.getBillNo(), flowVO.getSubmiter().getUserName(), flowVO.getRecipient().getUserName());
        //TODO 发送请求
        LoggerUtil.printLogger("【待办推送】,请求地址: {}", nxQxgParam.getQxg_origin() + NxQxgParam.todoApi);
        LoggerUtil.printLogger("【待办推送】,请求报文: {}", json.toString());
        String accessToken = QxgTokenUtil.getToken(nxQxgParam.getQxg_origin() + NxQxgParam.tokenApi, nxQxgParam.getQxg_appKey(), nxQxgParam.getQxg_secret());
        String resp = HttpUtil.createPost(nxQxgParam.getQxg_origin() + NxQxgParam.todoApi).header("Content-Type", "application/json").header("Authorization", accessToken).body(json.toString()).execute().body();
        //TODO 打印响应结果
        LoggerUtil.printLogger("【待办推送】,响应报文: {}", resp);
        JSONObject todoResult = JSONUtil.parseObj(resp);
        if (Constant.FW_SUCCESS_CODE != todoResult.getStr("operResult")) {
            throw new RuntimeException("【待办推送】,报错:" + todoResult.getStr("data"));
        }
    }
}
